﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DimensionData.Data2.Relations
{
    public class DDRelation : DRelation
    {
        public DDRelation(DTable upper, DTable lower)
            : base(upper, lower)
        {
        }

        protected override DTree OnGetTree(DContext context, DTreeNode node)
        {
            DData data = Lower.GetData(context);
            List<DDataRelation> relations = DMockData.GetDRelation(context.DocCode);
            for (int index = 0; index < relations.Count;)
            {
                if (relations[index].UpperCode != node.Code)
                {
                    relations.RemoveAt(index);
                }
                else
                {
                    index++;
                }
            }

            if (relations.Count > 0)
            {
                RemoveDDataNode(data, relations);
            }

            // 去除多余的节点
            return data.ConvertToTree();
        }

        private void RemoveDDataNode(DData data, List<DDataRelation> relations)
        {
            for (int index = 0; index < data.Nodes.Count;)
            {
                bool needRemove = true;
                foreach (var r in relations)
                {
                    if (r.LowerCode == data.Nodes[index].Code)
                    {
                        needRemove = false;
                        break;
                    }
                }

                if (needRemove)
                {
                    data.Nodes.RemoveAt(index);
                }
                else
                {
                    index++;
                }
            }
        }

        private void RemoveDDataNode(DDataNode node, List<DDataRelation> relations)
        {
            for (int index = 0; index < node.Nodes.Count; )
            {
                bool needRemove = true;
                foreach (var r in relations)
                {
                    if (r.LowerCode == node.Nodes[index].Code)
                    {
                        needRemove = false;
                        break;
                    }
                }

                if (needRemove)
                {
                    node.Nodes.RemoveAt(index);
                }
                else
                {
                    index++;
                }
            }
        }
    }
}
